package _67AddBinary;

public class CSolution {

  public static void main(String[] args) {
    System.out.println("aa");
    System.out.println(addBinary("1111", "1111"));
    System.out.println(addBinary("1010", "1011"));   //10101
    System.out.println(addBinary("111111111111111111111111111111111111111111111", "111111111111111111111111111111111111111111111"));
    System.out.println(addBinary("11", "1"));
  }

  private static String addBinary(String a, String b) {
    if (a.equals("0")) {
      return b;
    }
    if (b.equals("0")) {
      return a;
    }
    char[] aCahrs = a.toCharArray();
    char[] bCahrs = b.toCharArray();
    char[] charsShort = null;
    char[] charsLong = null;
    if (a.length() > b.length()) {
      charsShort = b.toCharArray();
      charsLong = new char[a.length() + 1];
      for (int i = a.length(); i > 0; i--) {
        charsLong[i] = aCahrs[i-1];
      }
    } else {
      charsShort = a.toCharArray();
      charsLong = new char[b.length() + 1];
      for (int i = b.length(); i > 0; i--) {
        charsLong[i] = bCahrs[i - 1];
      }
    }
    charsLong[0] = '0';
    int ext = 0;
    for (int i = charsLong.length - 1; i >= 0; i--) {
      int indexInShort = i - charsLong.length + charsShort.length;
      int longValue = Character.getNumericValue(charsLong[i]);
      int shortValue = indexInShort<0?0:Character.getNumericValue(charsShort[indexInShort]);
      if(ext+longValue+shortValue==0) {
        charsLong[i] = '0';
        ext = 0;
        continue;
      }
      if(ext+longValue+shortValue==1) {
        charsLong[i] = '1';
        ext = 0;
        continue;
      }
      if(ext+longValue+shortValue == 2) {
        charsLong[i] = ('0');
        ext = 1;
      }
    }
    String result = String.valueOf(charsLong);
    if(result.indexOf('0')==0) {
      return result.substring(1);
    }
    return result;
  }
}
